import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Card, Table, Button, Input, Select, Space, Tag, message, Avatar, Form, Row, Col } from 'antd'
import { 
  SearchOutlined, 
  ReloadOutlined, 
  UserOutlined, 
  PhoneOutlined, 
  MailOutlined,
  TrophyOutlined,
  DollarOutlined 
} from '@ant-design/icons'
import { fetchUserList, changeUserStatus } from '@/store/slices/appUserSlice'
import './index.scss'

const AppUserManagement = () => {
  const dispatch = useDispatch()
  const { userList, total, loading } = useSelector((state) => state.appUser)
  
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  
  // 搜索表单状态
  const [searchForm, setSearchForm] = useState({
    nickname: '',
    phone: '',
    status: null
  })

  // 加载用户列表
  useEffect(() => {
    dispatch(fetchUserList({ page, size: pageSize }))
  }, [dispatch, page, pageSize])

  // 搜索
  const handleSearch = () => {
    setPage(1)
    dispatch(fetchUserList({ 
      page: 1, 
      size: pageSize,
      ...searchForm 
    }))
  }

  // 重置
  const handleReset = () => {
    setSearchForm({
      nickname: '',
      phone: '',
      status: null
    })
    setPage(1)
    dispatch(fetchUserList({ page: 1, size: pageSize }))
  }

  // 切换用户状态
  const handleToggleStatus = async (record) => {
    const newStatus = record.status === 0 ? 1 : 0
    try {
      await dispatch(changeUserStatus({ 
        id: record.id, 
        status: newStatus 
      })).unwrap()
      message.success(`${newStatus === 0 ? '启用' : '禁用'}用户成功`)
      dispatch(fetchUserList({ page, size: pageSize, ...searchForm }))
    } catch (error) {
      message.error(`操作失败：${error}`)
    }
  }

  // 表格列配置
  const columns = [
    {
      title: '用户信息',
      key: 'userInfo',
      width: 250,
      render: (_, record) => (
        <Space>
          <Avatar 
            src={record.avatar} 
            icon={<UserOutlined />}
            size={40}
          />
          <div>
            <div style={{ fontWeight: 'bold' }}>{record.nickname || record.username || '未设置昵称'}</div>
            {record.username && (
              <div style={{ color: '#999', fontSize: '12px' }}>@{record.username}</div>
            )}
          </div>
        </Space>
      )
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 130,
      render: (phone) => phone ? (
        <span>
          <PhoneOutlined style={{ color: '#1890ff', marginRight: 4 }} />
          {phone}
        </span>
      ) : <span style={{ color: '#ccc' }}>未绑定</span>
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
      render: (email) => email ? (
        <span>
          <MailOutlined style={{ color: '#52c41a', marginRight: 4 }} />
          {email}
        </span>
      ) : <span style={{ color: '#ccc' }}>未绑定</span>
    },
    {
      title: '等级/积分',
      key: 'levelPoints',
      width: 140,
      render: (_, record) => (
        <div>
          <div style={{ marginBottom: 4 }}>
            <TrophyOutlined style={{ color: '#faad14', marginRight: 4 }} />
            Lv.{record.level || 1}
          </div>
          <div>
            <DollarOutlined style={{ color: '#13c2c2', marginRight: 4 }} />
            {record.points || 0}
          </div>
        </div>
      )
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (time) => {
        if (!time) return '-'
        try {
          return new Date(time).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          })
        } catch (e) {
          return time
        }
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 160,
      render: (time) => {
        if (!time) return '-'
        try {
          return new Date(time).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          })
        } catch (e) {
          return time
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center',
      render: (status) => (
        <Tag color={status === 0 ? 'success' : 'error'}>
          {status === 0 ? '正常' : '禁用'}
        </Tag>
      )
    }
  ]

  return (
    <div className="user-list-container">
      <Card>
        {/* 搜索区域 */}
        <Form layout="inline" style={{ marginBottom: 16 }}>
          <Form.Item label="昵称" style={{ marginBottom: 8 }}>
            <Input
              placeholder="请输入昵称"
              value={searchForm.nickname}
              onChange={(e) => setSearchForm({ ...searchForm, nickname: e.target.value })}
              style={{ width: 180 }}
              allowClear
            />
          </Form.Item>
          <Form.Item label="手机号" style={{ marginBottom: 8 }}>
            <Input
              placeholder="请输入手机号"
              value={searchForm.phone}
              onChange={(e) => setSearchForm({ ...searchForm, phone: e.target.value })}
              style={{ width: 180 }}
              allowClear
            />
          </Form.Item>
          <Form.Item label="状态" style={{ marginBottom: 8 }}>
            <Select
              placeholder="请选择状态"
              value={searchForm.status}
              onChange={(value) => setSearchForm({ ...searchForm, status: value })}
              style={{ width: 120 }}
              allowClear
            >
              <Select.Option value={null}>全部</Select.Option>
              <Select.Option value={0}>正常</Select.Option>
              <Select.Option value={1}>禁用</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item style={{ marginBottom: 8 }}>
            <Space>
              <Button 
                type="primary" 
                icon={<SearchOutlined />}
                onClick={handleSearch}
              >
                搜索
              </Button>
              <Button 
                icon={<ReloadOutlined />}
                onClick={handleReset}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 统计信息 */}
        <div style={{ marginBottom: 12, color: '#666', fontSize: '14px' }}>
          共 {total} 个用户
        </div>

        {/* 表格 */}
        <Table
          columns={columns}
          dataSource={userList}
          loading={loading}
          rowKey="id"
          scroll={{ x: 1200 }}
          pagination={{
            current: page,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPage(page)
              setPageSize(pageSize)
            }
          }}
        />
      </Card>
    </div>
  )
}

export default AppUserManagement
